﻿using AdverseEventReportSystem.BLL;
using AdverseEventReportSystem.Core;
using AdverseEventReportSystem.Model;
using AdverseEventReportSystem.Service;
using AdverseEventReportSystem.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AdverseEventReportSystem.Web.Areas.AdverseEvent
{
    public class AdverseEventSummaryController : BaseController
    {
        // GET: AdverseEvent/AdverseEventSummary
        public ActionResult Index()
        {
            ViewBag.CurrDepCode = loginUser.CurrDepCode;
            return View();
        }

        /// <summary>
        /// 统计列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Search()
        {
            SelectBuilder data = new SelectBuilder();
            data.From = "AdverseEvent";
            data.Select = "ID,EventTypeID,CreateTime";
            data.WhereSql = GetWhereSql();
            DataTable eventDt = BaseService<DataTable>.GetDataTableSelectBuilder(data);

            DataTable eventTypeDt = AdverseEventTypeService.GetAdverseEventTypeTable();
            DataTable dt = new DataTable();
            dt.Columns.Add("Month", typeof(string));
            foreach (DataRow item in eventTypeDt.Rows)
            {
                dt.Columns.Add("EventType" + item["ID"], typeof(int));
            }
            dt.Columns.Add("Total", typeof(int));


            while (endTime > startTime)
            {
                endTime = endTime.AddMonths(-1);
                if (endTime <= DateTime.Now)
                {
                    DataRow dr = dt.NewRow();
                    dr["Month"] = endTime.Month + "月";
                    dt.Rows.Add(dr);
                }
            }
            DataRow totalDr = dt.NewRow();
            totalDr["Month"] = "小计";
            dt.Rows.Add(totalDr);

            foreach (DataRow item in dt.Rows)
            {
                int rowTotal = 0;
                foreach (DataColumn column in dt.Columns)
                {
                    if (column.ColumnName == "Month") continue;
                    if (column.ColumnName == "Total" && item["Month"].ToString() != "小计")
                    {
                        item["Total"] = rowTotal;
                    }
                    else
                    {
                        int month = DataConvert.StrToInt(item["Month"].ToString().Replace("月", ""));
                        int eventTypeID = DataConvert.StrToInt(column.ColumnName.Replace("EventType", ""));

                        int count = (from r in eventDt.AsEnumerable()
                                     where r.Field<int>("EventTypeID") == eventTypeID && r.Field<DateTime>("CreateTime").Month == month
                                     select r).Count();

                        item[column.ColumnName] = count;
                        rowTotal += count;

                        if (item["Month"].ToString() == "小计")
                        {
                            item[column.ColumnName] = dt.AsEnumerable().Select(t => t.Field<int>(column.ColumnName)).Sum();
                        }
                    }
                }
            }

            var result = new { Rows = dt, EventType = eventTypeDt };
            return JsonDate(result);
        }

        /// <summary>
        /// 记录查询时间
        /// </summary>
        DateTime startTime, endTime;

        /// <summary>
        /// 获取查询条件
        /// </summary>
        /// <returns></returns>
        private string GetWhereSql()
        {
            int year = DataConvert.StrToInt(Request["year"]);
            int quarter = DataConvert.StrToInt(Request["quarter"]);
            int month = DataConvert.StrToInt(Request["month"]);
            string areaID = DataConvert.ToString(Request["areaID"]);

            string whereSql = "Status > 0";
            if (areaID == "-1")
            {
                whereSql += " and AreaID in ('" + string.Join("','", loginUser.DepartCode.Split('&')) + "')";
            }
            else
            {
                whereSql += string.Format(" and AreaID = '{0}'", areaID);
            }
            if (month == 0)
            {
                if (quarter == 0)
                {
                    startTime = new DateTime(year, 1, 1);
                    endTime = new DateTime(year, 1, 1).AddYears(1);
                    whereSql += string.Format(" and CreateTime >= '{0}' and CreateTime < '{1}'", startTime.ToString(), endTime.ToString());
                }
                else
                {
                    startTime = new DateTime(year, quarter * 3 - 2, 1);
                    endTime = new DateTime(year, quarter * 3 - 2, 1).AddMonths(3);
                    whereSql += string.Format(" and CreateTime >= '{0}' and CreateTime < '{1}'", startTime.ToString(), endTime.ToString());
                }
            }
            else
            {
                startTime = new DateTime(year, month, 1);
                endTime = new DateTime(year, month, 1).AddMonths(1);
                whereSql += string.Format(" and CreateTime >= '{0}' and CreateTime < '{1}'", startTime.ToString(), endTime.ToString());
            }

            return whereSql;
        }

        /// <summary>
        /// 压疮统计
        /// </summary>
        /// <param name="year"></param>
        /// <param name="quarter"></param>
        /// <param name="month"></param>
        /// <param name="areaID"></param>
        /// <returns></returns>
        public ActionResult YcSumIndex(int year, int quarter, int month, string areaID)
        {
            ViewBag.Year = year;
            ViewBag.Quarter = quarter;
            ViewBag.Month = month;
            ViewBag.AreaID = areaID;
            return View();
        }

        /// <summary>
        /// 压疮统计列表
        /// </summary>
        /// <returns></returns>
        public ActionResult YcSearch()
        {
            SelectBuilder data = new SelectBuilder();
            data.From = "AdverseEvent";
            data.Select = "ID,EventTypeID,CreateTime,Flag_Yc,(Select Value from AdverseEventModeRecord(nolock) where EventID = AdverseEvent.ID and ModeName='压伤类型') Value";
            data.WhereSql = GetWhereSql();
            DataTable eventDt = BaseService<DataTable>.GetDataTableSelectBuilder(data);

            DataTable dt = new DataTable();
            dt.Columns.Add("Month", typeof(string));
            dt.Columns.Add("YcKeNei", typeof(int));
            dt.Columns.Add("YcYuanWai", typeof(int));
            dt.Columns.Add("YcTaKe", typeof(int));
            dt.Columns.Add("Total", typeof(int));

            while (endTime > startTime)
            {
                endTime = endTime.AddMonths(-1);
                if (endTime <= DateTime.Now)
                {
                    DataRow dr = dt.NewRow();
                    dr["Month"] = endTime.Month + "月";
                    dt.Rows.Add(dr);
                }
            }
            DataRow totalDr = dt.NewRow();
            totalDr["Month"] = "小计";
            dt.Rows.Add(totalDr);

            foreach (DataRow item in dt.Rows)
            {
                int rowTotal = 0;
                foreach (DataColumn column in dt.Columns)
                {
                    if (column.ColumnName == "Month") continue;
                    if (column.ColumnName == "Total" && item["Month"].ToString() != "小计")
                    {
                        item["Total"] = rowTotal;
                    }
                    else
                    {
                        int month = DataConvert.StrToInt(item["Month"].ToString().Replace("月", ""));
                        int count = 0;
                        if (column.ColumnName == "YcKeNei")
                        {
                            count = (from r in eventDt.AsEnumerable()
                                     where (r.Field<string>("Value") == null ? false : r.Field<string>("Value").Split('#')[1] == "1") && r.Field<DateTime>("CreateTime").Month == month
                                     select r).Count();
                        }
                        else if (column.ColumnName == "YcYuanWai")
                        {
                            count = (from r in eventDt.AsEnumerable()
                                     where (r.Field<string>("Value") == null ? false : r.Field<string>("Value").Split('#')[0] == "1") && r.Field<DateTime>("CreateTime").Month == month
                                     select r).Count();
                        }
                        else if (column.ColumnName == "YcTaKe")
                        {
                            count = (from r in eventDt.AsEnumerable()
                                     where (r.Field<string>("Value") == null ? false : r.Field<string>("Value").Split('$')[0].Split('#')[2] == "1") && r.Field<DateTime>("CreateTime").Month == month
                                     select r).Count();
                        }

                        item[column.ColumnName] = count;
                        rowTotal += count;

                        if (item["Month"].ToString() == "小计")
                        {
                            item[column.ColumnName] = dt.AsEnumerable().Select(t => t.Field<int>(column.ColumnName)).Sum();
                        }
                    }
                }
            }

            var result = new { Rows = dt };
            return JsonDate(result);
        }

        /// <summary>
        /// 压疮上报打印预览
        /// </summary>
        /// <returns></returns>
        public ActionResult YcReport()
        {
            return View();
        }

        /// <summary>
        /// 压疮上报打印预览
        /// </summary>
        /// <returns></returns>
        public ActionResult YcReportPrint()
        {
            return View();
        }

        /// <summary>
        /// 获取压疮报表数据
        /// </summary>
        /// <returns></returns>
        [LoginAttribute(IsNeed = false)]
        public ActionResult GetYcReportPrint()
        {
            SelectBuilder data = new SelectBuilder();
            data.From = "AdverseEvent";
            data.Select = "ID,EventTypeID,CreateTime,PatientInTime,PatientBedNo,PatientName,PatientDiagnosis,AreaName,OccurrDepartName,Flag_Yc,TransferDepartName";
            data.WhereSql = GetWhereSql() + " and EventTypeID = 6";
            DataTable eventDt = BaseService<DataTable>.GetDataTableSelectBuilder(data);

            DataTable dt = new DataTable();
            dt.Columns.Add("Year");
            dt.Columns.Add("DepartmentName");
            dt.Columns.Add("CreateTime");
            dt.Columns.Add("PatientInTime");
            dt.Columns.Add("PatientBedNo");
            dt.Columns.Add("PatientName");
            dt.Columns.Add("PatientDiagnosis");
            dt.Columns.Add("Source1");
            dt.Columns.Add("Source2");
            dt.Columns.Add("BradenScore");
            dt.Columns.Add("SkinCondition1");
            dt.Columns.Add("SkinCondition2");
            dt.Columns.Add("SkinCondition3");
            dt.Columns.Add("SkinCondition4");
            dt.Columns.Add("ZhuanGui1");
            dt.Columns.Add("ZhuanGui2");
            dt.Columns.Add("ZhuanGui3");
            dt.Columns.Add("ZhuanGuiDate");
            dt.Columns.Add("TransferDepartName");

            var year = DateTime.Now.Year;

            foreach (DataRow row in eventDt.Rows)
            {
                DataRow dr = dt.NewRow();
                dr["Year"] = year;
                dr["DepartmentName"] = row["AreaName"];
                dr["CreateTime"] = DataConvert.StrToDateTime(row["CreateTime"], DateTime.Now).ToString("M/dd");
                dr["PatientInTime"] = DataConvert.StrToDateTime(row["PatientInTime"], DateTime.Now).ToString("M/dd");
                dr["PatientBedNo"] = row["PatientBedNo"];
                dr["PatientName"] = row["PatientName"];
                dr["PatientDiagnosis"] = row["PatientDiagnosis"];
                dr["TransferDepartName"] = row["TransferDepartName"].ToString().Replace("病区", ""); ;

                AdverseEventYcFanKui adverseEventYcFanKui = AdverseEventYcFanKuiService.GetQuerySingleByEventID(DataConvert.StrToInt(row["ID"]));
                if (adverseEventYcFanKui != null)
                {
                    dr["ZhuanGuiDate"] = DataConvert.StrToDateTime(adverseEventYcFanKui.ZgDate, DateTime.Now).ToString("M/dd");
                    switch (adverseEventYcFanKui.YhType)
                    {
                        case 0:
                            dr["SkinCondition1"] = "√";
                            break;
                        case 1:
                            dr["SkinCondition2"] = "√";
                            break;
                        case 2:
                            dr["SkinCondition3"] = "√";
                            break;
                        case 3:
                            dr["SkinCondition4"] = "√";
                            break;
                    }

                    switch (adverseEventYcFanKui.ZgType)
                    {
                        case 0:
                            dr["ZhuanGui2"] = "√";
                            break;
                        case 1:
                            dr["ZhuanGui1"] = adverseEventYcFanKui.ZgDepartmentName.Replace("病区", "");
                            break;
                    }
                }

                DataTable modeDt = AdverseEventModeRecordService.GetAdverseEventModeRecordTable(DataConvert.StrToInt(row["ID"]), DataConvert.StrToInt(row["EventTypeID"]));
                if (modeDt != null && modeDt.Rows.Count > 0)
                {
                    var d = (from r in modeDt.AsEnumerable()
                             where (r.Field<string>("ModeName") == "压伤类型")
                             select r).FirstOrDefault();


                    if (d != null && d["Value"].ToString() != "")
                    {
                        string ysValue = d["Value"].ToString();
                        if (ysValue.Split('#')[0] == "1")
                        {
                            dr["Source1"] = "√";
                        }

                        if (ysValue.Split('#')[1] == "1" || ysValue.Split('$')[0].Split('#')[2] == "1")
                        {
                            dr["Source2"] = "√";
                            if (DataConvert.StrToInt(row["Flag_Yc"]) == 0)
                            {
                                dr["Source2"] = row["OccurrDepartName"].ToString().Replace("病区", "");
                            }
                            else
                            {
                                if (ysValue.Split('$').Length > 1)
                                {
                                    OperateResult resultInfo = DepartmentManager.GetDetaildep(ysValue.Split('$')[1].Split('*')[1]);
                                    if (resultInfo.Result == 1)
                                    {
                                        if (resultInfo.Body != null)
                                            dr["Source2"] = (resultInfo.Body as AdverseEventReportSystem.BLL.ServiceReference1.tb_Department).DepartmentName.Replace("病区", "");
                                    }
                                }
                            }
                        }
                    }
                }
                dt.Rows.Add(dr);
            }

            var result = new { Rows = dt };
            return JsonDate(result);
        }
    }
}